<?php
namespace app\services;

use app\models\User;

class UsersService extends BaseService {
    private $defaultPassword = '123456';
    public $matrix = [
        'id' => 'id',
        'name' => 'name',
        'type' => ['user_type', '$v==1 && $v="root";
                                 $v==2 && $v=\Yii::t("common", "Operator");
                                 $v==3 && $v=\Yii::t("common", "Agent");
                                 $v==4 && $v=\Yii::t("common", "Advertiser");
                                 return $v;'],
        'email' => 'email',
        'resource' => 'resource',
        'status' => ['status', '$v==0 && $type=\Yii::t("common", "Pending");
                                $v==1 && $type=\Yii::t("common", "Normal");
                                $v==2 && $type=\Yii::t("common", "Normal");
                                return $type;'],
        'lastModifiedDate' => 'last_update',
        'operate' => ['id', 'return "edit,view";'],
    ];

    public function checkNewPassword($password, $confirm) {
        if (empty($password)) {
            $this->NG($this->t('common', 'Password cannot be empty!'));
        } else if ($password != $confirm) {
            $this->NG($this->t('common', 'Confirm password not match password!'));
        }
        return true;
    }

    public function saveNewUser($data, $isNew=true) {
        $data['status'] = 1;
        if ($isNew) {
            $this->checkNewPassword($data['password'], $data['confirm_password']);
            $this->I('password', $this->cryptPassword($data['password']));
        }
        // 新添加用户没有 id
        //$this->I('id', null);

        // $_POST['adnetwork_slot'] = '1';
        // $_POST['traffic_slot'] = implode(',', $this->I('traffic_slot'));
        // $_POST['media_slot'] = implode(',', $this->I('media_slot'));

        if (in_array(0, $this->I('adnetwork_slot'))) {
             $_POST['adnetwork_slot'] = '0';
        } else {
             $_POST['adnetwork_slot'] = implode(',', $this->I('adnetwork_slot'));
        }
        
        if (in_array(0, $this->I('traffic_slot'))) {
             $_POST['traffic_slot'] = '0';
        } else {
             $_POST['traffic_slot'] = implode(',', $this->I('traffic_slot'));
        }

        if (in_array(0, $this->I('media_slot'))) {
             $_POST['media_slot'] = '0';
        } else {
             $_POST['media_slot'] = implode(',', $this->I('media_slot'));
        }

        $newUser = $this->save('User', $data);
        $resource = ['user_id' => $newUser['id']];

        $this->I('id', null);

        // 保存广告主资源
        //前广告主数据设置为无效
        unset($_POST['id']);
        $ads = $this->I('advertiser_resource');
        $this->trySaveUserResource($newUser['id'], $ads, 2);

        // 保存用户资源
        //前广告主用户数据设置为无效
        $users = $this->I('govern_users');
        $this->trySaveUserResource($newUser['id'], $users, 1);
    }

    /**
     * 更新用户资源表数据
     */
    public function trySaveUserResource($userId, $resourceIds, $resourceType) 
    {   
        $this->update('UserResource', ['user_id'=>$userId, 'resource_type' => $resourceType]); 
        if (!$resourceIds || empty($resourceIds)) return true;
        foreach ($resourceIds as $resourceId) {
            $resource = [];
            $resource['user_id'] = $userId;
            $resource['resource_type'] = $resourceType;
            $resource['resource_id'] = $resourceId;
            $this->save('UserResource', $resource);
        }
    }

    public function updatePassword($password, $confirm, $userId='')
    {
        if($this->checkNewPassword($password, $confirm)) {
            !$userId && $userId = $this->S('user_id');
            return $this->saveOn('User', ['id' => $userId], ['password' => $this->cryptPassword($password)]);
        }
        return false;
    }

    public function cryptPassword($password) {
        $salt = $this->randString(2);
        return crypt($password, $salt);
    }

    public function validatePassword($password, $dbPassword) {
        return crypt($password, $dbPassword)===$dbPassword;
    }

    public function resetPassword($userId) {
        $password = $this->defaultPassword;
        $confirm = $password;
        return $this->updatePassword($password, $confirm, $userId);
    }

    public function chkLogin($useremail, $password) {
        $user = User::find()->where(['email'=>$useremail])->one();
        if ($user) {
            if($this->validatePassword($password, $user->password)) {
                return $this->writeSession($user);
            }
            $this->NG($this->t('common', 'Password not correct!'));
        }
        $this->NG($this->t('common', 'Email not registed!'));
    }

    public function getUserRank($user) {
        if ($user['user_type'] == 1) return 'root';
        if ($user['user_type'] == 2) return 'operator';
        if ($user['user_type'] == 3) return 'agent';
        if ($user['user_type'] == 4) return 'advertiser';
    }

    public function writeSession($user) {
        $this->S('is_root', $user['is_root']);
        $this->S('user_type', $user['user_type']);
        $this->S('user_name', $user['name']);
        $this->S('user_id', $user['id']);
        $this->S('user_email', $user['email']);
        $this->S('user_rank', $this->getUserRank($user));
        $this->S('adnetwork_slot', explode(',', $user['adnetwork_slot']));
        //如果一个用户有banner权限，那么他也具有cpe权限
        $traffic_slot = explode(',', $user['traffic_slot']);
        if(in_array(1,$traffic_slot)){
            array_push($traffic_slot,'5');
        }
        $this->S('traffic_slot',$traffic_slot);
        $this->S('media_slot', explode(',', $user['media_slot']));
        
        // 设置用户所辖广告主名单
        $domainAdvertisers = $this->getUserAdvertisers($user);
        $this->S('domainAdvertisers', $domainAdvertisers);
        $this->S('LastRequestTime', time());
        
        // 默认设置第一个广告主为UI焦点广告主
        // foreach ($domainAdvertisers as $ad) {
        //     $this->S('advertiser_id', $ad['id']);
        //     break;
        // }
        $this->S('advertiser_id', 0);
        return true;
    }

    /**
     * 刷新当前用户的 session
     */
    public function freshSession() {
        $user = $this->M('User', $this->S('user_id'));
        $this->writeSession($user);
    }

    public function getUserSubIds($userId, &$userResource) {
        $Ids=[];
        if(isset($userResource[$userId])) {
            foreach ($userResource[$userId] as &$resource) {
                if(isset($resource['is_used'])) {
                    continue;
                } else {
                    $resource['is_used'] = 1;
                    if ($resource['resource_type'] == 2) {
                        $Ids[] = $resource['resource_id'];
                    } else {
                        $Id = $this->getUserSubIds($resource['resource_id'], $userResource);
                        $Ids = array_merge($Ids,$Id);
                    }
                }
            }
        } 
        return $Ids;
    }

    public function getUserAdvertisers($user, $resourceType='2', $filter=true) {
        $ads = $this->getAll('Advertiser');
        if (in_array($user['user_type'], [2, 3, 4])) {
            $userResource = $this->getAll('UserResource', ['status' => 1]);
            $userResource = $this->arrayGroup($userResource, 'user_id');
            $adIds = $this->getUserSubIds($user['id'], $userResource);
            $domainAds = [];
            foreach ($ads as $ad) {
                if (in_array($ad['id'], $adIds)) {
                    $domainAds[] = $ad;
                }
            }
            $ads = $domainAds;
        }
        if ($filter) {
            $ads = $this->fieldsMap(['id' => 'id', 'name' => 'name'], $ads);
            $ads = $this->getField($ads, ['id', 'name']);
        }
        return $ads;
    }

    /**
     * 获取运营/代理商和广告主(自己）的下属广告主 id 集合
     */
    public function getUserSubordinateIds($user, $resourceType='2')
    {
        $adIds = [];
        $resource['user_id'] = $user['id'];
        $resource['resource_type'] = $resourceType;
        $resource['status'] = 1;
        $resources = $this->getAll('UserResource', $resource);
        if (in_array($user['user_type'], [2, 3, 4])) {
            foreach ($resources as $resource) {
                $adIds[] = $resource['resource_id'];
            }
        }
        return $adIds;
    }

    public function getAllUsers() {
        $datas = $this->getAll('User');
        $advertisers = $this->getAll('Advertiser');
        foreach ($datas as &$user) {
            $user['resource'] = '';
            $rank = $this->getUserRank($user); 
            if ($rank == 'root') {
                $allAd = $this->t('common', 'All Advertiser');
                $resource = [$allAd];
            } else {
                $ads = [];
                $resource = '';
                $userResource = $this->getAll('UserResource', ['status' => 1]);
                $userResource = $this->arrayGroup($userResource, 'user_id');
                $adIds = $this->getUserSubIds($user['id'], $userResource);
                foreach ($advertisers as $ad) {
                    if (in_array($ad['id'], $adIds)) {
                        $ads[] = $ad['name'];
                    }
                }
                $resource = implode(', ', $ads);
            }
            $user['resource'] = $resource;
        }
        return $this->fieldsMap($this->matrix, $datas);
    }

    public function getTrafficTypes() {
        return [1 => $this->t('common', 'Display'),
                2 => $this->t('user', 'Video'),
                3 => $this->t('common', 'Mobile'),
                4 => $this->t('common', 'Mobile Video')];
    }

    public function getAdspaceMedias() {
        $sql = 'select id, case ad_network_id when 1 then concat("vm_", media_name)
                                              when 2 then concat("ac_", media_name)   
                                              end media_name from {{%adnetwork_media}}';
        $medias = $this->query($sql);
        return $medias;
    }

    public function getAllAdNetWork() {
        $datas = $this->getAll('AdNetwork');
        $matrix = [
            'id'        => 'id',
            'channel'   => ['name', '$v=="vamaker"&&$v=\Yii::t("resource", "ValueMaker");
                                     return $v;'],
        ];
        $datas = $this->fieldsMap($matrix, $datas);
        return $datas;
    }

}// end of user service declaration
